//
//  NearbyVC.m
//  WuyouTang
//
//  Created by YunBao on 2018/7/27.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "NearbyVC.h"

#import "AFNetworking.h"
#import "NearbyVideoModel.h"
#import "NearbyCell.h"
#import "YBGetVideoObj.h"
#import "YBCitySelVC.h"
#import "searchVC.h"

@import CoreLocation;
@interface NearbyVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,CLLocationManagerDelegate>
{
    NSInteger _paging;
    NSString *_currentCity;
    CLLocationManager   *_lbsManager;
    BOOL _isSelfLoc;
}
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSArray *models;
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)UILabel *headerTitle;
@end

@implementation NearbyVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[PublicObj publicInstance]addCusDelayedRemove];
    
    if (_dataArray.count <= 0) {
        [self pullData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.leftBtn.hidden = NO;
    [self.leftBtn setImage:[UIImage imageNamed:@"home_search"] forState:0];
    self.rightBtn.hidden = NO;
    [self.rightBtn setImage:[UIImage imageNamed:@"同城-定位"] forState:0];
    self.rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 6);
    self.rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -6, 0, 0);
    [self.rightBtn setTitleColor:UIColor.whiteColor forState:0];
    self.titleL.text = YZMsg(@"同城");
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate = (id) self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = Normal_Color;
    _currentCity = @"";
    _isSelfLoc = NO;
    YBWeakSelf;
    [[RKLBSManager shareManager] startLocation];
    [[RKLBSManager shareManager] locationComplete:^(BOOL isSuc, NSArray<CLPlacemark *> *placemarks, NSArray<NSString *> *pcaArray) {
        if ([PublicObj checkNull:_currentCity]) {
            _currentCity = [PublicObj checkNull:minstr(pcaArray[1])]?@"":pcaArray[1];
            if ([_currentCity hasSuffix:@"市"]) {
                _currentCity = [_currentCity substringToIndex:_currentCity.length-1];
            }
            [weakSelf changeName:_currentCity];
            [weakSelf pullData];
        }
    }];
    
    self.dataArray = [NSMutableArray array];
    self.models = [NSArray array];
    _paging = 1;
    
//    _url = [NSString stringWithFormat:@"Video.getNearby&uid=%@&lng=%@&lat=%@",[Config getOwnID],[cityDefault getLocationLng],[cityDefault getLocationLat]];
    
    _url = @"Video.getNearby";
    
    [self.view addSubview:self.collectionView];
    
}

- (void)clickNaviLeftBtn{
    searchVC *search = [[searchVC alloc]init];
    search.searchFrom = SearchFrom_City;
    search.curCity = _currentCity;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:search animated:YES];
}
- (void)clickNaviRightBtn{
    [self clickChangeBtn];
}
- (NSArray *)models {
    NSMutableArray *m_array = [NSMutableArray array];
    for (NSDictionary *dic in _dataArray) {
        NearbyVideoModel *model = [NearbyVideoModel modelWithDictionary:dic];
        [m_array addObject:model];
    }
    _models = m_array;
    return _models;
}

-(void)pullData {
   _collectionView.userInteractionEnabled = NO;
    //NSString *url = [NSString stringWithFormat:@"%@&p=%ld&city=%@",_url,(long)_paging,_currentCity];
    NSDictionary *postDic = @{
        @"lng":[CityDefault getLocationLng],
        @"lat":[CityDefault getLocationLat],
        @"p":@(_paging),
        @"city":_currentCity,
    };
    [WYNetworking postWithUrl:_url Dic:postDic Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
        _collectionView.userInteractionEnabled = YES;
        if (code == 0) {
            NSArray *infoA = [NSArray arrayWithArray:info];
            if (_paging == 1) {
                [_dataArray removeAllObjects];
            }
            if (infoA.count <= 0) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [_dataArray addObjectsFromArray:infoA];
            }
            if (_dataArray.count > 0) {
                [PublicView hiddenTextNoData:_collectionView];
            }else{
                [PublicView showTextNoData:_collectionView text1:@"" text2:YZMsg(@"暂无附近视频哦~") centerY:0.8];
            }
            [_collectionView reloadData];
            
        }else{
            if (_dataArray) {
                [_dataArray removeAllObjects];
            }
            [_collectionView reloadData];
            [PublicView showTextNoData:_collectionView text1:@"" text2:YZMsg(@"暂无附近视频哦~") centerY:0.8];
        }
    } Fail:^(id fail) {
        _collectionView.userInteractionEnabled = YES;
        
        _collectionView.userInteractionEnabled = YES;
        if (_dataArray) {
            [_dataArray removeAllObjects];
        }
        [_collectionView reloadData];
        [PublicView showTextNoData:_collectionView text1:@"" text2:YZMsg(@"暂无附近视频哦~") centerY:0.8];
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
    }];
    
}
#pragma mark - CollectionView 代理
/*
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;{
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NearbyHeader" forIndexPath:indexPath];
        [reusableView addSubview:self.headerView];
        return reusableView;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(_window_width, 40);
}
*/
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 2;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.models.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NearbyCell *cell = (NearbyCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"NearbyCell" forIndexPath:indexPath];
    NearbyVideoModel *model = _models[indexPath.row];
    cell.isSelfLoc = _isSelfLoc;
    cell.model = model;
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *vidoeID = minstr([_dataArray[indexPath.row] valueForKey:@"id"]);
    [YBGetVideoObj lookManeger].fromWhere = @"NearbyVC";
    [YBGetVideoObj lookManeger].videoID = vidoeID;
    [YBGetVideoObj lookManeger].playIndex = (int)indexPath.row;
    [YBGetVideoObj lookManeger].videoList = [_dataArray mutableCopy];
    [YBGetVideoObj lookManeger].paging = (int)_paging;
    [YBGetVideoObj lookManeger].baseUrl = _url;
    [[YBGetVideoObj lookManeger]goLookVC];
}

#pragma mark - set/get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(_window_width/2-1, (_window_width/2-1) * 1.4);
        flow.minimumLineSpacing = 2;
        flow.minimumInteritemSpacing = 2;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,64+statusbarHeight, _window_width, _window_height-49-ShowDiff-64-statusbarHeight) collectionViewLayout:flow];
        [_collectionView registerNib:[UINib nibWithNibName:@"NearbyCell" bundle:nil] forCellWithReuseIdentifier:@"NearbyCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"NearbyHeader"];
        _collectionView.backgroundColor = Normal_Color;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.mj_footer  = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            _paging ++;
            [self pullData];
        }];
        
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            _paging = 1;
            [self pullData];
            
        }];
    }
    return _collectionView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 40)];
        _headerView.backgroundColor = NaviBg_Color;
        
        _headerTitle = [[UILabel alloc]init];
        _headerTitle.text = [NSString stringWithFormat:@"%@:%@",YZMsg(@"定位城市"),_currentCity];
        _headerTitle.font = SYS_Font(12);
        _headerTitle.textColor = RGB_COLOR(@"#ffffff", 0.53);
        [_headerView addSubview:_headerTitle];
        
        UIButton *changeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        changeBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
        [changeBtn setTitle:YZMsg(@"切换") forState:0];
        changeBtn.titleLabel.font = SYS_Font(12);
        [changeBtn setTitleColor:_headerTitle.textColor forState:0];
        [changeBtn setImage:[UIImage imageNamed:@"更多-箭头"] forState:0];
        [changeBtn addTarget:self action:@selector(clickChangeBtn) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:changeBtn];
        
        [_headerTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_headerView.mas_left).offset(15);
            make.height.centerY.equalTo(_headerView);
            make.right.lessThanOrEqualTo(changeBtn.mas_left).offset(-10);
        }];
        [changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.centerY.equalTo(_headerView);
            make.right.equalTo(_headerView.mas_right).offset(-15);
            make.width.mas_greaterThanOrEqualTo(46);
        }];
        
        [_headerView layoutIfNeeded];
        [changeBtn setImageEdgeInsets:UIEdgeInsetsMake(0, changeBtn.titleLabel.size.width, 0, -changeBtn.titleLabel.size.width)];
        [changeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -changeBtn.imageView.size.width-1, 0, changeBtn.imageView.size.width+1)];
        
    }
    return _headerView;
}
-(void)clickChangeBtn {
    YBCitySelVC *selVC = [[YBCitySelVC alloc]init];
    YBWeakSelf;
    selVC.citySelEvent = ^(NSString *cityName) {
        _currentCity = cityName;
        [weakSelf changeName:cityName];
        _paging = 1;
        [weakSelf pullData];
    };
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:selVC animated:YES];
}

-(void)changeName:(NSString *)cityName {
    if ([cityName containsString:[CityDefault getLocationCity]] || [[CityDefault getLocationCity] containsString:cityName]) {
        _isSelfLoc = YES;
    }else {
        _isSelfLoc = NO;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [PublicObj updataNewCity:cityName];
        _headerTitle.text = [NSString stringWithFormat:@"%@:%@",YZMsg(@"定位城市"),_currentCity];
        [self.rightBtn setTitle:cityName forState:0];
    });
   
}


@end
